package com.sola.oauthserver.config2;

import com.sola.oauthserver.security.MyPasswordEncoder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;

//默认拦截顺序：Order=100
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
   //定义用户信息Bean，也可以单独写个类实现UserDetailsService接口，
   // 定义从数据库获取的实际的用户名密码权限等，
   // 赋予给security的User，这样就不需要内存方式定义user了
    @Bean
    @Override
    public UserDetailsService userDetailsServiceBean() throws Exception {
        return super.userDetailsServiceBean();
    }


    //定义用户授权Bean，一般不用修改
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    //内存方式定义user1和user2
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                //spring boot2.0以后都需要声明密码编码器，继承了父类：passwordEncoder
                //此自定义MyPasswordEncoder类中有两个方法，一个是加密方式，一个是验证方式
                .passwordEncoder(new MyPasswordEncoder())
                //user1普通用户
                .withUser("user1")
                .password("123456")
                .roles("USER")
                .and()
                //user2管理员用户
                .withUser("user2")
                .password("123456")
                .roles("USER","ADMIN");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //需要把csrf禁用，否者会报无法跨域访问的错误，spring cloud中一般都需要此设置

        http.httpBasic().and()
                .authorizeRequests()
                .antMatchers("/login")//"/oauth/**"
                .permitAll()
                .anyRequest()
                .authenticated()
                .and().csrf().disable();

        /*http.authorizeRequests()
                //管理员权限才有权利进行/**路径下的DELETE操作
                .antMatchers(HttpMethod.DELETE,"/**")
                .hasRole("ADMIN")
                .antMatchers("/oauth/**").permitAll()
                .anyRequest()
                .authenticated()
                .and()
                //这里需要支持httpBasic的验证，否者通过postman无法提交认证用户信息
                .httpBasic();*/
    }
}
